import os

import pygame

import data
import spritesheet
import settings

# Game loop should blit these if blood is enabled...
blood_sprites = pygame.sprite.Group()

image_file = data.filepath(os.path.join('image','blood0.png'))
images = spritesheet.SpriteSheet(image_file).load_strip(
    (64,64), 6, margin=(0,0), padding=(0,0), colorkey=-1, orient='v')
del image_file

class Blood(pygame.sprite.Sprite):
    
    time_to_live = 60.      # seconds
    frame_interval = .1     # seconds
    
    def __init__(self, position, angle, magnitude=1.0):
        super(Blood, self).__init__(blood_sprites)
        self.image = None  #images[0].copy()
        self.rect = None #self.image.get_rect(center=position)
        self.position = position
        self.angle = angle
        self.magnitude = magnitude
        self.elapsed = 0.0
    
    @staticmethod
    def rotimage(image, angle, factor = 1., cache = {}):
        key = (image, int(angle / 9.) % 40, factor)
        if key not in cache:
            cache[key] = pygame.transform.rotozoom(image, angle, factor)
        return cache[key]
                
    def update(self, dt):
        self.elapsed += dt
        if self.elapsed <= self.magnitude:
            n = len(images) - 1
            n = min(n, int(round(n*self.elapsed/self.frame_interval)) )
            self.image = self.rotimage(images[n], self.angle)
            self.image.set_colorkey(images[n].get_colorkey())
            self.rect = self.image.get_rect(center=self.position)
        elif self.elapsed < self.time_to_live:
            factor = (self.elapsed-self.magnitude) / (self.elapsed-self.time_to_live)
            alpha = 255 - 255 * factor
            self.image.set_alpha(alpha)
        else:
            try:
                blood_sprites.remove(self)
            except:
                pass

if __name__ == '__main__':
    from math import atan2, pi
    from pygame.locals import *
    def angle_of(origin, end_point):
        x1,y1 = origin
        x2,y2 = end_point
        return (180 - atan2(y2-y1,x2-x1) * 180.0 / pi + 90.0) % 360.0
    pygame.init()
    screen = pygame.display.set_mode((400,400))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    while 1:
        dt = clock.tick(25) / 1000.0
        for e in pygame.event.get():
            if e.type == MOUSEBUTTONDOWN:
                angle = angle_of(screen_rect.center, e.pos)
                Blood(e.pos, angle, 1.0)
        screen.fill((0,0,0))
        blood_sprites.update(dt)
        blood_sprites.draw(screen)
        pygame.display.flip()
